package com.nsgf.library.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.DatabaseUtils;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.flexbox.FlexboxLayout;
import com.google.android.flexbox.FlexboxLayout.LayoutParams;
import com.kunminx.binding_recyclerview.adapter.SimpleDataBindingAdapter;
import com.nsgf.library.data.api.APIs;
import com.nsgf.library.data.bean.Shop;
import com.nsgf.library.ui.product.ConfirmOrderActivity;
import com.nsgf.library.ui.product.ProductDetailActivity;
import com.nsgf.library.utils.StringUtil;
import com.zhht.htzx.R;
import com.nsgf.library.data.bean.ProductDetailBean;
import com.zhht.htzx.databinding.DialogProductSpecBinding;
import com.zhht.htzx.databinding.ItemDialogSpecBinding;

import java.util.ArrayList;
import java.util.List;

public class ProductSpecDialog extends Dialog {
    private Context context;
    private OnSpecSelectedListener listener;
    private String selectedColor = "";
    private int quantity = 1;
    private ProductDetailBean productDetailBean;

    public interface OnSpecSelectedListener {
        void onSpecSelected(String color, int quantity);
    }

    public ProductSpecDialog(@NonNull Context context, ProductDetailBean detailBean, OnSpecSelectedListener listener) {
        super(context, R.style.BottomDialog);
        this.context = context;
        this.listener = listener;
        this.productDetailBean = detailBean;
    }

    DialogProductSpecBinding specBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = View.inflate(context, R.layout.dialog_product_spec, null);
        setContentView(view);

        specBinding = DataBindingUtil.bind(view);
        specBinding.setVm(productDetailBean);
        // 设置弹窗位置和动画
        Window window = getWindow();
        if (window != null) {
            window.setGravity(Gravity.BOTTOM);
            window.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.WRAP_CONTENT);
            window.setWindowAnimations(R.style.DialogAnimation);
        }

        initViews();
        setupSpecOptions();
    }

    private void initViews() {
        // 关闭按钮
        findViewById(R.id.ivClose).setOnClickListener(v -> dismiss());

        // 数量加减按钮
        EditText etQuantity = findViewById(R.id.etQuantity);
        Button btnMinus = findViewById(R.id.btnMinus);
        Button btnPlus = findViewById(R.id.btnPlus);

        btnMinus.setOnClickListener(v -> {
            if (quantity > 1) {
                quantity--;
                etQuantity.setText(String.valueOf(quantity));
            }
        });

        btnPlus.setOnClickListener(v -> {
            quantity++;
            etQuantity.setText(String.valueOf(quantity));
        });

        // 确认按钮
        findViewById(R.id.btnConfirm).setOnClickListener(v -> {
            if (selectedColor.isEmpty()) {
                Toast.makeText(context, "请选择规格", Toast.LENGTH_SHORT).show();
                return;
            }
            if (listener != null) {
                listener.onSpecSelected(selectedColor, quantity);
            }
            dismiss();
        });
    }

    SimpleDataBindingAdapter<ProductDetailBean.GroupedPropertiesDTO, ItemDialogSpecBinding> mAdapter;

    private void setupSpecOptions() {
        RecyclerView recyclerView = findViewById(R.id.recyclerView);

        mAdapter = new SimpleDataBindingAdapter<ProductDetailBean.GroupedPropertiesDTO, ItemDialogSpecBinding>(context, R.layout.item_dialog_spec, new DiffUtil.ItemCallback<ProductDetailBean.GroupedPropertiesDTO>() {
            @Override
            public boolean areItemsTheSame(@NonNull ProductDetailBean.GroupedPropertiesDTO oldItem, @NonNull ProductDetailBean.GroupedPropertiesDTO newItem) {
                return false;
            }

            @Override
            public boolean areContentsTheSame(@NonNull ProductDetailBean.GroupedPropertiesDTO oldItem, @NonNull ProductDetailBean.GroupedPropertiesDTO newItem) {
                return false;
            }
        }) {
            @Override
            protected void onBindItem(ItemDialogSpecBinding binding, ProductDetailBean.GroupedPropertiesDTO item, RecyclerView.ViewHolder holder) {

                binding.setVm(item);
                for (ProductDetailBean.GroupedPropertiesDTO.ValueNameVosDTO vosDTO : item.getValueNameVos()) {

                    TextView button = createSpecButton(vosDTO.getValueName());
                    button.setOnClickListener(v -> {

                        updateSpecButtonState(binding.flexColor, button);
                        updateSelectedSpecText();
                    });
                    binding.flexColor.addView(button);

                }
                binding.flexColor.setFlexWrap(com.google.android.flexbox.FlexWrap.WRAP);
                list.add(binding.flexColor);
            }
        };
        recyclerView.setAdapter(mAdapter);
        mAdapter.submitList(productDetailBean.getGroupedProperties());
        recyclerView.setLayoutManager(new LinearLayoutManager(context));

    }

    private List<FlexboxLayout> list = new ArrayList<>();

    private TextView createSpecButton(String text) {
        TextView button = new TextView(context);
        LayoutParams params = new LayoutParams(
                LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT
        );
        params.setMargins(0, 0, 16, 16);
        button.setLayoutParams(params);
        button.setText(text);
        button.setBackgroundResource(R.drawable.bg_spec_button);
        button.setTextColor(context.getResources().getColor(android.R.color.black));
        return button;
    }

    private void values() {

        updateSelectedSpecText();
    }

    private void updateSpecButtonState(FlexboxLayout layout, TextView selectedButton) {
        for (int i = 0; i < layout.getChildCount(); i++) {
            View child = layout.getChildAt(i);
            if (child instanceof TextView) {
                TextView button = (TextView) child;
                if (button == selectedButton) {
                    button.setBackgroundResource(R.drawable.bg_spec_button_selected);
                    button.setSelected(true);
                    button.setTextColor(context.getResources().getColor(android.R.color.white));
                } else {
                    button.setSelected(false);
                    button.setBackgroundResource(R.drawable.bg_spec_button);
                    button.setTextColor(context.getResources().getColor(android.R.color.black));
                }
            }
        }
    }

    private void updateSelectedSpecText() {
        selectedColor = "";
        for (FlexboxLayout layout : list) {

            for (int i = 0; i < layout.getChildCount(); i++) {
                View child = layout.getChildAt(i);
                if (child instanceof TextView) {
                    TextView button = (TextView) child;
                    if (button.isSelected()) {

                        if (StringUtil.isEmpty(selectedColor))
                            selectedColor += button.getText().toString();
                        else
                            selectedColor += "|" + button.getText().toString();
                    }
                }
            }
        }
        for (ProductDetailBean.SkusDTO dto : productDetailBean.getSkus()) {
            if (selectedColor.equals(dto.getSpecLink())) {
                specBinding.tvDialogProductStock.setText(dto.getStockSrc());
                specBinding.tvDialogPrice.setText("￥" + APIs.df.format(dto.getPrice() / 100));
                break;
            }
        }
    }
}